# -*- coding: utf-8 -*-
from db.mysql import MysqlClient
import requests
from common.helper import Helper
from common.config import *
from urllib.parse import urlencode
from itertools import product
from pyquery import PyQuery as pq
import json
class Spider(object):
    def __init__(self):
        self.name = "全能保镖个人综合意外险"
        self.mysql = MysqlClient()
    # 生产产品数据
    def genProductInfo(self):
        jbs = self.getProfessionInfo()
        first_level = [ name["name"] for name in jbs if name["label"]=="1"]
        second_level = [name["name"] for name in jbs if name["label"]=="2"]
        third_level = [name["name"] for name in jbs if name["label"]=="3"]
        fourth_level = [name["name"] for name in jbs if name["label"]=="4"]
        fifth_level = [name["name"] for name in jbs if name["label"]=="5"]
        six_level = [name["name"] for name in jbs if name["label"]=="6"]
        plan = {
            "planA": {
                "days": ["1y"],
                "people_count": ["1"],
                "accident_death": ["200000", "300000"],
                "accident_contagion": ["200000"],
                "airplane_death": ["500000", "2000000"],
                "common_traffic": ["100000", "300000"],
                "vacation_death": ["100000", "200000"],
                "accident_medical": ["10000", "30000"],
                "accident_hospital": ["50/天", "150/天"],
                "accident_ambulance": ["200", "800"],
                "professions": [
                    json.dumps(first_level,ensure_ascii=False),
                    json.dumps(second_level,ensure_ascii=False),
                    json.dumps(third_level,ensure_ascii=False),
                    json.dumps(fourth_level,ensure_ascii=False),
                    json.dumps(fifth_level,ensure_ascii=False),
                    json.dumps(six_level,ensure_ascii=False),
                ]
            },
            "planB": {
                "days": ["1y"],
                "people_count": ["1"],
                "accident_death": ["100000"],
                "accident_contagion": ["100000"],
                "myselfDriver": ["200000"],
                "accident_medical": ["", "30000"],
                "accident_ambulance": ["", "400"],
                "professions":[
                    json.dumps(first_level, ensure_ascii=False),
                    json.dumps(second_level, ensure_ascii=False),
                    json.dumps(third_level, ensure_ascii=False),
                    json.dumps(fourth_level, ensure_ascii=False),
                    json.dumps(fifth_level, ensure_ascii=False),
                    json.dumps(six_level, ensure_ascii=False),
                ]
            }
        }
        for k in plan:
            if k == "planA":
                for v in product(plan[k]["days"],plan[k]["people_count"],plan[k]["accident_death"],plan[k]["accident_contagion"],plan[k]["airplane_death"],plan[k]["common_traffic"],plan[k]["vacation_death"],plan[k]["accident_medical"],plan[k]["accident_hospital"],plan[k]["accident_ambulance"],plan[k]["professions"]):
                    data = {
                        "days":v[0],
                        "people_count":v[1],
                        "accident_death":v[2],
                        "accident_contagion":v[3],
                        "airplane_death":v[4],
                        "common_traffic":v[5],
                        "vacation_death":v[6],
                        "accident_medical":v[7],
                        "accident_hospital":v[8],
                        "accident_ambulance":v[9],
                        "professions":v[10],
                    }
                    if data["accident_death"] == "300000":
                        extCode = "planB3"
                    else:
                        extCode = "planB1"
                    if "16岁以下儿童（不含学龄前儿童）" in data["professions"]:
                        level = "1"
                    elif "无业人员" in data["professions"]:
                        level = "2"
                    elif "畜牧工作人员" in data["professions"]:
                        level = "3"
                    elif  "布景搭设人员" in data["professions"]:
                        level = "4"
                    elif "机动三轮车工人" in data["professions"]:
                        level = "5"
                    else:
                        level = "6"
                    price = self.requestJson(extCode, level)
                    data["professions"] = "'" + data["professions"] + "'"
                    data["name"] = self.name
                    data["company"] = "太平洋保险"
                    data["price"] = price
                    Sql = 'INSERT INTO `accident`(`days`,`people_count`,`accident_death`,`accident_contagion`,`airplane_death`,`common_traffic`,`vacation_death`,`accident_medical`,`accident_hospital`,`accident_ambulance`,`professions`,`name`,`company`,`price`)VALUES("{days}","{people_count}","{accident_death}","{accident_contagion}","{airplane_death}","{common_traffic}","{vacation_death}","{accident_medical}","{accident_hospital}","{accident_ambulance}",{professions},"{name}","{company}","{price}")'
                    self.mysql.cursor.execute( Sql.format(**data))
                    self.mysql._conn.commit()
                    print(Sql.format(**data) )

            else:
                for v in product( plan[k]["days"],plan[k]["people_count"],plan[k]["accident_death"],plan[k]["accident_contagion"],plan[k]["myselfDriver"],plan[k]["accident_medical"],plan[k]["accident_ambulance"],plan[k]["professions"]):
                    data = {
                        "days":v[0],
                        "people_count":v[1],
                        "accident_death":v[2],
                        "accident_contagion":v[3],
                        "myselfDriver":v[4],
                        "accident_medical":v[5],
                        "accident_ambulance":v[6],
                        "professions":v[7],
                    }
                    if data["accident_medical"] == "":
                        extCode = "planC1"
                    else:
                        extCode = "planC3"
                    if "16岁以下儿童（不含学龄前儿童）" in data["professions"]:
                        level = "1"
                    elif "无业人员" in data["professions"]:
                        level = "2"
                    elif "畜牧工作人员" in data["professions"]:
                        level = "3"
                    elif  "布景搭设人员" in data["professions"]:
                        level = "4"
                    elif "机动三轮车工人" in data["professions"]:
                        level = "5"
                    else:
                        level = "6"
                    price = self.requestJson( extCode,level )
                    data["professions"] = "'" + data["professions"] + "'"
                    data["name"] = self.name
                    data["company"] = "太平洋保险"
                    data["price"] = price
                    Sql = 'INSERT INTO `accident`(`days`,`people_count`,`accident_death`,`accident_contagion`,`myselfDriver`,`accident_medical`,`accident_ambulance`,`professions`,`name`,`company`,`price`)VALUES("{days}","{people_count}","{accident_death}","{accident_contagion}","{myselfDriver}","{accident_medical}","{accident_ambulance}",{professions},"{name}","{company}","{price}")'
                    self.mysql.cursor.execute( Sql.format( **data ))
                    self.mysql._conn.commit()
                    print( Sql.format( **data ) )

    # 执行爬虫
    def requestJson(self,plan,level):
        data = {
            "plan": plan,
            "productCode": "81091100",
            "jobLevel": level,
        }
        print( data )
        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["c_url"] + payload ,headers=domain[self.name]["header"])
        if r.status_code == 200 and "premium" in r.text :
            price = Helper.decimalParse( r.json()["premium"])
            return price
    # 获取职业信息
    def getProfessionInfo(self):
        all_jobs = []
        job_url = "https://www.cpic.com.cn/market/c/2019-12-18/1587802.shtml?SCsite=healthLb"
        jobs = lambda x: requests.get(url=x, headers=domain[self.name]["header"]).text
        html = jobs(job_url).encode('ISO-8859-1').decode(requests.utils.get_encodings_from_content(jobs(job_url))[0])
        doc = pq(html)
        items = doc("#occupation option").items()
        for item in items:
            jid = (item.attr("value"))
            if len(jid) == 0:
                continue
            data = {
                "name": item.text(),
                "id": jid
            }
            payload = 'parentId=' + data["id"] + '&num=1'
            header = headers_raw_to_dict(
                b'''
                Accept: application/json, text/javascript, */*; q=0.01
                Accept-Encoding: gzip, deflate, br
                Accept-Language: zh-CN,zh;q=0.9
                Connection: keep-alive
                Content-Length: 25
                Content-Type: application/x-www-form-urlencoded; charset=UTF-8
                Cookie: JSESSIONID=BB1E08FA838A0C3DEAF1F03C138F011E; s_fid=08205C3CE6FC55DF-0060697F20118BB9; clientId=000a-c06d-016f3a954d87; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2216efcb00342c-0b6cc1fb1b6046-2393f61-2073600-16efcb0034610a%22%2C%22%24device_id%22%3A%2216efcb00342c-0b6cc1fb1b6046-2393f61-2073600-16efcb0034610a%22%2C%22props%22%3A%7B%22%24latest_referrer%22%3A%22%22%2C%22%24latest_referrer_host%22%3A%22%22%2C%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_utm_source%22%3A%22PC%22%2C%22%24latest_utm_medium%22%3A%22PCerweima%22%7D%7D; s_nr=1586836104386; SESSION_COOKIE=264_1_defaultgroup_camsi-pc-web-app.a0f4faae-75ae-11ea-8bad-feb90b6aa3e9; cpic_product_ids=81091100%2C
                Host: www.cpic.com.cn
                Origin: https://www.cpic.com.cn
                Referer: https://www.cpic.com.cn/market/c/2019-12-18/1587802.shtml?SCsite=healthLb
                Sec-Fetch-Mode: cors
                Sec-Fetch-Site: same-origin
                User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Mobile Safari/537.36
                X-Requested-With: XMLHttpRequest
                '''
            )
            profess = lambda: requests.post(url="https://www.cpic.com.cn/mall/sale/wwb/loadSelectedData",
                                            headers=header, data=payload).json()
            for pro in profess()["occupationList2"]:
                all_jobs.append(pro)

        return all_jobs
